package com.ffapp.helper.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisFragment;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.bean.ParamListData;
import com.ffapp.helper.util.CountDown;
import com.ffapp.helper.util.EditTextUtil;
import com.ffapp.helper.util.SoftKeyBoardListener;
import com.ffapp.helper.util.SubstringUtil;
import com.ffapp.helper.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.LogUtil;

public class CameraFragment extends BasisFragment {

    static CameraFragment fragment;

    public static CameraFragment newInstance() {
        if (fragment == null) {
            fragment = new CameraFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> terminalList;
    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private PopHandle popHandle;

    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    initSettingSaveThred();
                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if (!isFinish && !getActivity().isFinishing()) {
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_camera);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        terminalList = new ArrayList<>();
    }

    public void setList(String sMsgObjString, int type) {
        terminalList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {

            //APN
            String camera = SubstringUtil.subString(sMsgObjString, "Camera1 Atrr:");
            String[] cameras = camera.split(",");
            if(camera.length()<1){
                cameras = new String[]{"无", "无", "无", "", "1", ""};
            }

            //硬件接口
            ArrayList<String> hardwareInterfaceList = new ArrayList<>();
            hardwareInterfaceList.add("无");
            hardwareInterfaceList.add("RS232-1");
            hardwareInterfaceList.add("RS485-1");
            hardwareInterfaceList.add("RS485-2");
            hardwareInterfaceList.add("RS485-3");
            terminalList.add(new ParamListData("硬件接口", 1, "" + cameras[0], hardwareInterfaceList, false));
            //序号
            terminalList.add(new ParamListData("序号", 2, "" + cameras[4], false));

            //类别
            ArrayList<String> typeList = new ArrayList<>();
            typeList.add("无");
            typeList.add("SXH");
            terminalList.add(new ParamListData("类别", 1, "" + cameras[1], typeList, false));

            //画面大小
            ArrayList<String> pictureSizeList = new ArrayList<>();
            pictureSizeList.add("NONE");
            pictureSizeList.add("160x120");
            pictureSizeList.add("320x240");
            pictureSizeList.add("640x480");
            pictureSizeList.add("1280x1024");
            terminalList.add(new ParamListData("画面大小", 1, "" + cameras[2], pictureSizeList, false));

            //摄像头ID
            terminalList.add(new ParamListData("摄像头ID", 2, "" + cameras[3], true));


            //画面大小
            ArrayList<String> sbjgList = new ArrayList<>();
            sbjgList.add("5");
            sbjgList.add("10");
            sbjgList.add("20");
            sbjgList.add("60");
            terminalList.add(new ParamListData("上报间隔", 1, "" + cameras[5], sbjgList, true));
        }

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return terminalList == null ? 0 : terminalList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData terminalListData = terminalList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);

                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = terminalList.get(curPosition);
                        data.setValue(s.toString());
                    }
                });

                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    atShowResult.setLength(0);
                    BleUtils.stopNotify();
                    isFinish = true;
                    dismissProgress();
                    mCountDownTimer.cancel();
                    if (!TextUtils.isEmpty(saveResult.toString())) {
                        if (popHandle == null) {
                            popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                        }
                        popHandle.show();
                    } else {
                        showToast("保存成功");
                    }
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveFailure();
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });

    }

    public void initSettingSaveThred() {

        String toSet = "";
        for (ParamListData paramListData : terminalList){
            String value = (paramListData.getValue() == null) ? paramListData.getKey() : paramListData.getValue();
            if(value.equals("NONE")){
                value = "无";
            }
            toSet += value+",";
        }
        try {
            toSet = toSet.substring(0,toSet.length() - 1);
            toSet = HexUtil.chineseWordToGbk("AT+CAMPARA="+toSet) + "0D0A";
            mCountDownTimer.start();
            BleUtils.write(toSet, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                    if (current == total) {

                    }
                }

                @Override
                public void onWriteFailure(final BleException exception) {
                    saveFailure();
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }

    private void saveFailure() {
        saveResult.append("保存失败" + "\r\n");
        BleUtils.stopNotify();
        isFinish = true;
        dismissProgress();
        mCountDownTimer.cancel();
        PopHandle popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
        popHandle.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }
}
